package com.entfrm.biz.system.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.entfrm.base.api.R;
import com.entfrm.biz.system.entity.TOrder;
import com.entfrm.biz.system.entity.User;
import com.entfrm.biz.system.service.OrderService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.util.Date;

@Controller
@AllArgsConstructor
public class OrderController {
    @Autowired
    private OrderService orderService;

    private QueryWrapper<TOrder> getBuyQueryWrapper(User user) {
        return new QueryWrapper<TOrder>().eq(ObjectUtil.isNotNull(user.getId()), "buyer_id", user.getId());
    }
    private QueryWrapper<TOrder> getSaleQueryWrapper(User user) {
        return new QueryWrapper<TOrder>().eq(ObjectUtil.isNotNull(user.getId()), "saler_id", user.getId());
    }
    /**
     * 我买的订单
     * @return
     */
    public R getMyBuyOrders(Page page, User user){
        IPage<TOrder> orderIPage = orderService.page(page,getBuyQueryWrapper(user));
//        EntfrmUser user = SecurityUtil.getUser();
//        Integer userId = user.getId();
//        return orderService.getMyBuyOrders(userId);
        return R.ok(orderIPage.getRecords(), orderIPage.getTotal());
    }
    /**
     * 我买的订单
     * @return
     */
    public R getMySaleOrders(Page page, User user){
        IPage<TOrder> orderIPage = orderService.page(page,getSaleQueryWrapper(user));
        return R.ok(orderIPage.getRecords(), orderIPage.getTotal());
    }
    /**
     * 所有订单
     * @return
     */
    public R getAllOrders(Page page, User user){
        IPage<TOrder> orderIPage = orderService.page(page,new QueryWrapper<>());
        return R.ok(orderIPage.getRecords(), orderIPage.getTotal());
    }

    /**
     *生成订单
     * @param tOrder 订单
     * @return
     */
    public R save(TOrder tOrder){
        tOrder.setCreatTime(new Date());
        tOrder.setOrderStatus("1");
        orderService.save(tOrder);
        return R.ok();
    }

    /**
     *修改订单
     * @param tOrder 订单
     * @return
     */
    public R update(TOrder tOrder){
        orderService.updateById(tOrder);
        return R.ok();
    }
}
